<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { asyncRouterMap } from '@/router'
import { useI18n } from '@/hooks/web/useI18n'
import type { RouteRecordRaw } from 'vue-router'
import { useAppStore } from '@/store/modules/app'

const appStore = useAppStore()
const hoverColor = ref(appStore.getTheme.elColorPrimary)

const { t } = useI18n()
const route = useRoute()
const router = useRouter()

interface RouteItem extends RouteRecordRaw {
  meta?: {
    title?: string
    [key: string]: any
  }
  children?: RouteItem[]
}

const currentSecondMenu = ref<RouteItem | null>(null)

// 获取二级菜单下面的三四级菜单
const findRouteByNameInSecondLevel = (
  routes: RouteItem[],
  targetName: string
): RouteItem | null => {
  // 遍历一级路由
  for (const firstLevelRoute of routes) {
    // 检查是否有children且是数组
    if (firstLevelRoute.children && Array.isArray(firstLevelRoute.children)) {
      // 遍历二级路由
      for (const secondLevelRoute of firstLevelRoute.children) {
        // 检查路由名称是否匹配
        if (secondLevelRoute.name === targetName) {
          return secondLevelRoute
        }
      }
    }
  }
  return null // 未找到返回null
}

const handleGoFourthRouteItem = (routeItem: RouteItem) => {
  console.log(routeItem.path, 'routeItem')
  if (routeItem.path) {
    router.push(routeItem.path)
  }
}

onMounted(() => {
  const foundRoute = findRouteByNameInSecondLevel(
    asyncRouterMap as RouteItem[],
    route.name as string
  )
  currentSecondMenu.value = foundRoute
})
</script>

<template>
  <ContentWrap>
    <div
      class="w-100% min-h-10 mb-7"
      v-for="thirdRouteItem in currentSecondMenu?.children"
      :key="thirdRouteItem.name"
    >
      <div class="border-b-1 border-b-solid border-b-[#ccc] pb-2 font-bold">
        {{ $t(thirdRouteItem?.meta?.title) }}
      </div>
      <div class="mt-3">
        <span
          v-for="fourthRouteItem in thirdRouteItem?.children"
          class="mr-5 text-[14px] cursor-pointer text-[#67696b] hover:!text-[var(--hover-color)]"
          @click="handleGoFourthRouteItem(fourthRouteItem)"
          :style="{ '--hover-color': hoverColor }"
          :key="fourthRouteItem.name"
        >
          {{ $t(fourthRouteItem?.meta?.title) }}
        </span>
      </div>
    </div>
  </ContentWrap>
</template>
